package com.dk.category.service;

import com.dk.category.constants.CategoryConstants;
import com.dk.category.constants.RedisConstants;
import com.dk.category.dto.CategoryDTO;
import com.dk.category.entity.CategoryEntity;
import com.dk.category.service.CategoryService;
import com.dk.feign.api.Category2AdminService;
import com.ts.common.core.utils.ConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Component
public class CategoryHotJob {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 每30分钟计算一次热度，保存到数据库中
     */
    @Transactional
    public void calculateCircleHot(Integer circleHotNum) {
        // 查询全部圈子
        List<CategoryDTO> categoryDTOS = categoryService.list(null);

        // 遍历圈子
        for (CategoryDTO categoryDTO : categoryDTOS) {
            // 判断圈子状态是否正常
            Integer status = categoryDTO.getStatus();
            if (status == 1) {
                // 获取计算热度的相关数据
                Integer userNum = categoryDTO.getUserNum(); // 圈子人数
                Integer topicNum = categoryDTO.getTopicNum(); // 圈子帖子数
                Integer exposure = categoryDTO.getExposure(); // 圈子曝光量
                Integer adminId = categoryDTO.getAdminId(); // 圈主权重
                Date createTime = categoryDTO.getCreateTime();

                // 准备热度相关数据
                Double d1 = userNum*0.2;
                Double d2 = topicNum*0.4;
                Integer d3 = exposure;
                Integer d4 = adminId;
                Long d5 = createTime.getTime();

                // 计算热度
                Double d = d1 + d2 + d3 + d4 + d5;
                double hot = Math.log(d);


                // 保存到数据库中
                categoryDTO.setHot(hot);
                CategoryEntity categoryEntity = ConvertUtils.sourceToTarget(categoryDTO, CategoryEntity.class);
                categoryService.updateById(categoryEntity);
            }
        }
        // 默认热门圈子个数为10
        int defaultNum = 10;

        // 如果不为空，替换
        if (!ObjectUtils.isEmpty(circleHotNum)) {
            defaultNum = circleHotNum;
        }

        // 获取数据库最新数据
        List<CategoryDTO> hotCircleList = categoryService.getHot(defaultNum);
        List<CategoryDTO> circleList = categoryService.list(null);

        // 将最新数据放到redis缓存
        redisTemplate.opsForHash().put(RedisConstants.HASH_KEY, RedisConstants.HASH_HOT_KEY, hotCircleList);
        redisTemplate.opsForHash().put(RedisConstants.HASH_KEY, RedisConstants.HASH_LIST_KEY, circleList);
    }
}
